package com.app.couponsharelife.ui.main.me.invite

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.sharesdk.onekeyshare.OnekeyShare
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.data.bean.Poster
import com.app.couponsharelife.data.bean.RemoteResultBean
import com.app.couponsharelife.data.bean.ShareBannerBean
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.dialog.BotShareDialog
import com.app.couponsharelife.ui.listener.OnClickListener
import com.app.couponsharelife.utils.AppUtils
import com.mylhyl.zxing.scanner.encode.QREncode
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.tencent.mm.opensdk.modelmsg.WXImageObject
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_share_invite_pic.*
import kotlinx.android.synthetic.main.share_invite_pic_item.view.*
import java.util.HashMap


class ShareInvitePicActivity : BaseActivity() {
    private var index=0
    private var inviteCode = ""
    private var registerLink = ""
    private var qrcodeBitmap: Bitmap? = null
    private var itmView:View?=null
    private var bitmap: Bitmap? = null
    private var shareView:View?=null
    private var api: IWXAPI? = null
    private var layoutManager:LinearLayoutManager?=null
    private var shareInvitePicAdapter:MyAdapter?=null
    private var dataList= arrayListOf<Poster>()
    private var isFirst=true
    override val viewLayoutId: Int get() = R.layout.activity_share_invite_pic
    override fun initViews() {
        AppUtils.initImmersionBar(this,false)
        initToolBar()
        shareInvite_llLink.setOnClickListener {
            if (registerLink != "")
                copyInviteCode(registerLink,"注册口令已复制")
            else
                showToastMsg("邀请码错误，请退出重试")
        }
        shareInvite_llShare.setOnClickListener {
            BotShareDialog(this, R.style.DialogStyle, object : OnClickListener {
                override fun click(arg1: Int, arg2: Any) {
                    if (itmView!=null) {
                        bitmap = Bitmap.createBitmap(itmView!!.width, itmView!!.height, Bitmap.Config.ARGB_8888)
                        val canvas = Canvas(bitmap)
                        itmView!!.draw(canvas)
                        sharePic(arg1)
                    }else{
                        showToastMsg("数据出错，请稍后重试！")
                    }
                }
            }).show()
            //showShare()
        }
        shareInvite_tvCopy.setOnClickListener {
            if (inviteCode.isNotEmpty())
                copyInviteCode(inviteCode,"邀请码已复制")
            else
                showToastMsg("邀请码错误，请退出重试")
        }
        //getShareAppUrl()
        getShareBanner()
    }

    private fun sharePic(arg1: Int) {
        // 创建对应大小的bitmap
        if (bitmap == null) {
            showToastMsg("请选择要分享的图片")
            return
        }
        val image = WXImageObject(bitmap)

        val msg = WXMediaMessage()
        msg.mediaObject = image

        val thumb = Bitmap.createScaledBitmap(bitmap, 150, 150, true)
        msg.thumbData = AppUtils.bmpToByteArray(thumb, true)

        val req = SendMessageToWX.Req()    //创建一个请求对象
        req.message = msg  //把msg放入请求对象中
        if (arg1 == 1)
            req.scene = SendMessageToWX.Req.WXSceneTimeline    //设置发送到朋友圈
        else
            req.scene = SendMessageToWX.Req.WXSceneSession   //设置发送给朋友
        req.transaction = AppUtils.buildTransaction("img")  //这个tag要唯一,用于在回调中分辨是哪个分享请求
        if (api == null) api = WXAPIFactory.createWXAPI(this@ShareInvitePicActivity, Contacts.WECHAT_APP_ID)
        api!!.sendReq(req)   //如果调用成功微信,会返回true
    }
    private fun showShare() {
        if (shareView==null){
            return
        }
        val oks = OnekeyShare()
        //关闭sso授权
        oks.disableSSOWhenAuthorize()

        // title标题，微信、QQ和QQ空间等平台使用
        oks.setTitle("分享")
        // titleUrl QQ和QQ空间跳转链接
        oks.setTitleUrl("http://sharesdk.cn")
        // text是分享文本，所有平台都需要这个字段
        oks.text = "我是分享文本"
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        oks.setViewToShare(shareView)
        //oks.setImagePath("/sdcard/test.jpg")//确保SDcard下面存在此张图片
        // url在微信、微博，Facebook等平台中使用
        //oks.setUrl("http://sharesdk.cn")
        // comment是我对这条分享的评论，仅在人人网使用
        //oks.setComment("我是测试评论文本")
        // 启动分享GUI
        oks.show(this)
    }
    private fun copyInviteCode(code: String,message:String) {
        //获取剪贴板管理器：
        val cm = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        // 创建普通字符型ClipData
        val mClipData = ClipData.newPlainText("Label", code)
        // 将ClipData内容放到系统剪贴板里。
        cm.primaryClip = mClipData
        showToastMsg(message)
    }

    private fun initToolBar() {
        shareInvite_ivBack.setOnClickListener { finish() }
        shareInvite_tvTitle.text = "邀请好友"
    }
    private fun initRecyclerView() {
        if (inviteCode == "" || qrcodeBitmap == null) {
            showToastMsg("邀请码错误，请退出重试")
            return
        }
        layoutManager = LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false)//GalleryLayoutManager(GalleryLayoutManager.HORIZONTAL)
        mRecyclerView.setItemViewCacheSize(20)
        mRecyclerView.layoutManager = layoutManager
        shareInvitePicAdapter=MyAdapter()
        mRecyclerView.adapter=shareInvitePicAdapter
        itmView=layoutManager!!.findViewByPosition(0)
    }

    /*override fun initViewModel() {
        if (mViewModel == null) mViewModel = ViewModelProviders.of(this).get(MeViewModel::class.java)
        if (!mViewModel!!.userCenter()!!.hasObservers()) {
            mViewModel!!.userCenter()!!.observe(this, Observer {
                if (it == null) {
                    dismissProgressDialog()
                    showToastMsg("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                        showProgressDialog("请稍候")
                    }
                    PageStatus.Error -> {
                        dismissProgressDialog()
                        mViewModel!!.freshUserCenter(hashMapOf(), false)
                        showToastMsg(parseErrorDate(it.error!!.message).tip)
                    }
                    PageStatus.Empty -> {
                        dismissProgressDialog()
                        mViewModel!!.freshUserCenter(hashMapOf(), false)
                        showToastMsg("数据出错啦")
                    }
                    PageStatus.Content -> {
                        dismissProgressDialog()
                        mViewModel!!.freshUserCenter(hashMapOf(), false)
                        if (it.data!!.code == 200 && it.data.data != null && it.data.data!!.requestcode != "") {
                            inviteCode = it.data.data!!.requestcode
                            registerLink = Contacts.REGISTER_URL + inviteCode
                            qrcodeBitmap = QREncode.Builder(this@ShareInvitePicActivity)
                                    .setColor(ContextCompat.getColor(this, R.color.black))//二维码颜色
                                    .setMargin(1)//二维码边框
                                    .setSize(500)//二维码等比大小
                                    .setContents(registerLink)//二维码内容
                                    .build().encodeAsBitmap()
                            initRecyclerView()
                        } else {
                            showToastMsg("邀请码获取失败")
                        }
                    }
                }
            })
        }
        userCenter()
    }

    private fun userCenter() {
        val map = HashMap<String, String>()
        map["userId"] = AppUtils.getString(Contacts.USERID, "")
        mViewModel?.freshUserCenter(map, true)
    }*/
    private fun getShareBanner(){
        showProgressDialog("加载中...")
        val map = HashMap<String, String>()
        map["userId"]= AppUtils.getString(Contacts.USERID,"")
        RetrofitWorker.retrofitWorker.getShareBanner(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object :DisposableObserver<RemoteResultBean<ShareBannerBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<ShareBannerBean>) {
                        dismissProgressDialog()
                        if (it.code==200){
                            registerLink = it.data!!.url!!
                            inviteCode=it.data!!.code?:""
                            if (inviteCode.contains("邀请码：")){
                                inviteCode=inviteCode.replace("邀请码：","")
                            }
                            shareInvite_tvCode.text = inviteCode
                            dataList.clear()
                            dataList.addAll(it.data!!.posters!!)
                            dataList[0].isCheck=true
                            qrcodeBitmap = QREncode.Builder(this@ShareInvitePicActivity)
                                    .setColor(ContextCompat.getColor(this@ShareInvitePicActivity, R.color.black))//二维码颜色
                                    .setMargin(1)//二维码边框
                                    .setSize(450)//二维码等比大小
                                    .setContents(registerLink)//二维码内容
                                    .build().encodeAsBitmap()
                            initRecyclerView()
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        if (e is OtherException){
                            showToastMsg(e.msg)
                        }else{
                            showToastMsg("网络加载出错了！")
                        }
                    }
                })
    }
    private fun getShareAppUrl(){
        val map = HashMap<String, String>()
        map["userId"]= AppUtils.getString(Contacts.USERID,"")
        RetrofitWorker.retrofitWorker.getShareAppUrl(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<String>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<String>) {
                        if (it.code==200){
                            registerLink = it.data!!
                            if (registerLink.isNotEmpty()){
                                val arr=registerLink.split("invitationCode=")
                                if (arr.size>1){
                                    inviteCode=arr[1]
                                }
                            }
                            qrcodeBitmap = QREncode.Builder(this@ShareInvitePicActivity)
                                    .setColor(ContextCompat.getColor(this@ShareInvitePicActivity, R.color.black))//二维码颜色
                                    .setMargin(1)//二维码边框
                                    .setSize(500)//二维码等比大小
                                    .setContents(registerLink)//二维码内容
                                    .build().encodeAsBitmap()
                            initRecyclerView()
                        } else {
                            showToastMsg("邀请码获取失败")
                        }
                    }

                    override fun onError(e: Throwable) {

                    }
                })
    }

    override fun onDestroy() {
        super.onDestroy()
        AppUtils.destroyImmersionBar(this)
    }
    private inner class MyAdapter:RecyclerView.Adapter<RecyclerView.ViewHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            val view=LayoutInflater.from(this@ShareInvitePicActivity).inflate(R.layout.share_invite_pic_item, parent, false)
            return MyHolder(view)
        }

        override fun getItemCount(): Int {
            return dataList.size
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            if (dataList.isNotEmpty()){
                if (holder is MyHolder){
                    val poster=dataList[position]
                    Glide.with(holder.itemView).asBitmap()
                            .apply(RequestOptions().transform(RoundedCorners( 2)))
                            .load(Contacts.APP_LIFE_IMGURL +poster.path)
                            .into(holder.ivBg!!)
                    holder.tvCode!!.text = inviteCode
                    holder.tvCode!!.setTextColor(Color.parseColor("#${poster.fontColor}"))
                    holder.tvStep!!.setTextColor(Color.parseColor("#${poster.fontColor}"))
                    holder.vWX!!.setBackgroundColor(Color.parseColor("#${poster.fontColor}"))
                    holder.vWX1!!.setBackgroundColor(Color.parseColor("#${poster.fontColor}"))
                    holder.tvStep1!!.setTextColor(Color.parseColor("#${poster.fontColor}"))
                    Glide.with(holder.itemView).asBitmap()
                            .apply(RequestOptions().transform(RoundedCorners( 2)))
                            .load(qrcodeBitmap)
                            .into(holder.ivCode!!)
                    var isCheck=poster.isCheck?:false
                    if (isCheck){
                        holder.ivCheck!!.setImageResource(R.drawable.ic_act_good_share_select)
                    }else{
                        holder.ivCheck!!.setImageResource(R.drawable.ic_act_good_share_no_select)
                    }
                    if (0==position&&isFirst){
                        itmView=holder.itemView
                    }
                    holder.itemView.setOnClickListener {
                        if (index!=position){
                            isFirst=false
                            dataList[position].isCheck=true
                            dataList[index].isCheck=false
                            index=position
                            itmView=holder.itemView
                            shareInvitePicAdapter!!.notifyDataSetChanged()
                        }
                    }
                }
            }
        }
    }
    private inner class MyHolder(itemview:View):RecyclerView.ViewHolder(itemview){
        var ivBg:ImageView?=null
        var tvCode:TextView?=null
        var tvStep:TextView?=null
        var tvStep1:TextView?=null
        var ivCode:ImageView?=null
        var vWX:View?=null
        var vWX1:View?=null
        var ivCheck:ImageView?=null
        init {
            ivBg=itemview.ivSharePic
            tvCode=itemview.tvInviteCode
            tvStep=itemview.tvStep1
            tvStep1=itemview.tvStep2
            vWX=itemview.viewX
            vWX1=itemview.viewX1
            ivCode=itemview.ivInviteLinkQRCode
            ivCheck=itemview.ivInviteCheck
        }
    }
}
